﻿using DefaultScope;
using Fabrikam.Client.DataModel;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage.Streams;
using Windows.UI.Core;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media.Imaging;
using System.Runtime.InteropServices.WindowsRuntime;
using GalaSoft.MvvmLight.Messaging;

namespace Fabrikam.Client.ViewModels
{
    public class SplitPageViewModel : ViewModelBase
    {

        private ObservableCollection<ServiceTicketViewModel> serviceTickets = new ObservableCollection<ServiceTicketViewModel>();



        private ServiceTicketViewModel serciceTicket;
        public ServiceTicketViewModel ServiceTicket
        {
            get
            {
                return serciceTicket;
            }
            set
            {
                if (value == serciceTicket)
                    return;

                serciceTicket = value;

                if (serciceTicket != null)
                    serciceTicket.ServiceTicket.PropertyChanged += async (o, e) =>
                        {
                            if (e.PropertyName == "CustomerID")
                                await serciceTicket.GetCustomerAndImage();

                        };

                base.RaisePropertyChanged(() => ServiceTicket);
            }
        }

        // The Guid is the potential selected ticket id
        private RelayCommand<Guid?> loadCommand;
        public RelayCommand<Guid?> LoadCommand
        {
            get
            {
                if (loadCommand != null) return loadCommand;

                loadCommand = new RelayCommand<Guid?>(async (serviceTicketId) =>
                {
                    await GetServiceTickets();

                    if (serviceTicketId.HasValue)
                        this.ServiceTicket = this.ServiceTickets.FirstOrDefault(s => s.ServiceTicket.ServiceTicketID == serviceTicketId.Value);
                });

                return loadCommand;
            }
        }

        // The Guid is the refresh service ticket
        private RelayCommand<Guid> refreshCommand;
        public RelayCommand<Guid> RefreshCommand
        {
            get
            {
                if (refreshCommand != null) return refreshCommand;

                refreshCommand = new RelayCommand<Guid>(async (serviceTicketId) =>
                {
                    // get the refreshed id from db
                    var ticketRefreshed = await DataService.Current.GetTicketById(serviceTicketId);

                    // get the same ticket from list if available
                    var ticket = this.ServiceTickets.FirstOrDefault(t => t.ServiceTicket.ServiceTicketID == serviceTicketId);

                    if (ticket != null)
                    {
                        ticket.ServiceTicket.Closed = ticketRefreshed.Closed;
                        ticket.ServiceTicket.CustomerID = ticketRefreshed.CustomerID;
                        ticket.ServiceTicket.Description = ticketRefreshed.Description;
                        ticket.ServiceTicket.EscalationLevel = ticketRefreshed.EscalationLevel;
                        ticket.ServiceTicket.Opened = ticketRefreshed.Opened;
                        ticket.ServiceTicket.StatusValue = ticketRefreshed.StatusValue;
                        ticket.ServiceTicket.Title = ticketRefreshed.Title;
                    }
                    else
                    {
                        this.ServiceTickets.Add(new ServiceTicketViewModel(ticketRefreshed));
                    }

                });

                return refreshCommand;
            }
        }

        private RelayCommand deleteCommand;
        public RelayCommand DeleteCommand
        {
            get
            {
                if (deleteCommand != null) return deleteCommand;

                deleteCommand = new RelayCommand(async () =>
                {
                    // Create the message dialog and set its content and title
                    var messageDialog = new MessageDialog(
                        "Are you sure that you want to delete this item", "Delete item.");

                    // Add commands and set their callbacks
                    messageDialog.Commands.Add(new UICommand("Yes", async (command) =>
                    {
                        // Delete the ticket
                        await DataService.Current.DeleteTicket(this.ServiceTicket.ServiceTicket.ServiceTicketID);

                        // Delete from internal list
                        var ticket = this.ServiceTickets.FirstOrDefault(t => t.ServiceTicket.ServiceTicketID == this.ServiceTicket.ServiceTicket.ServiceTicketID);
                        if (ticket != null)
                            this.ServiceTickets.Remove(ticket);

                    }));

                    messageDialog.Commands.Add(new UICommand("No", (command) =>
                    {
                    }));

                    // Set the command that will be invoked by default
                    messageDialog.DefaultCommandIndex = 0;
                    messageDialog.CancelCommandIndex = 1;

                    // Show the message dialog
                    await messageDialog.ShowAsync();
                });

                return deleteCommand;
            }
        }

        private RelayCommand editCommand;
        public RelayCommand EditCommand
        {
            get
            {
                if (editCommand != null) return editCommand;

                editCommand = new RelayCommand(async () =>
                {
                    SettingsFlyoutItem sf = new SettingsFlyoutItem();
                    Context.SettingFlyoutItemViewModel.InitServiceTicket(this.ServiceTicket.ServiceTicket);
                    sf.Width = 500;
                    var isOk = await sf.ShowIndependentAsync();

                    if (isOk)
                        this.RefreshCommand.Execute(Context.SettingFlyoutItemViewModel.ServiceTicketID);
                });

                return editCommand;
            }
        }

        private RelayCommand addCommand;
        public RelayCommand AddCommand
        {
            get
            {
                if (addCommand != null) return addCommand;

                addCommand = new RelayCommand(async () =>
                {
                    SettingsFlyoutItem sf = new SettingsFlyoutItem();
                    Context.SettingFlyoutItemViewModel.InitServiceTicket(null);
                    sf.Width = 500;
                    var isOk = await sf.ShowIndependentAsync();

                    if (isOk)
                        this.RefreshCommand.Execute(Context.SettingFlyoutItemViewModel.ServiceTicketID);
                });

                return addCommand;
            }
        }
        private async Task GetServiceTickets()
        {
            ServiceTickets.Clear();

            var lst = await DataService.Current.GetTickets();

            foreach (var serviceTicket in lst)
                ServiceTickets.Add(new ServiceTicketViewModel(serviceTicket));

        }


        public ObservableCollection<ServiceTicketViewModel> ServiceTickets
        {
            get
            {
                return serviceTickets;
            }
            set
            {
                if (value == serviceTickets)
                    return;

                serviceTickets = value;

                base.RaisePropertyChanged(() => ServiceTickets);
            }
        }

        public SplitPageViewModel()
        {
            if (IsInDesignMode)
            {
                this.ServiceTickets = DataDesignerService.GetServiceTickets();
                this.ServiceTicket = this.ServiceTickets.FirstOrDefault();
            }
        }
    }
}
